package lime.browser.command;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import lime.common.LimeException;
import lime.model.Document;
import lime.service.RepositoryService;
import lime.service.SpringApplicationContext;

import org.apache.commons.io.IOUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.program.Program;
import org.eclipse.ui.handlers.HandlerUtil;

import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfId;

public class OpenContentHandler extends AbstractHandler {

	private RepositoryService repositoryService;

	public OpenContentHandler() {
		super();
		repositoryService = (RepositoryService) SpringApplicationContext.getBean("repositoryService");
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object element = structuredSelection.getFirstElement();
			if (element != null && element instanceof Document) {
				Document document = (Document) element;
				IDfId objectId = new DfId(document.getObjectId());
				try {
					IDfSysObject sysObject = (IDfSysObject) repositoryService.getSession().getObject(objectId);
					if (sysObject.getContentSize() > 0) {
						InputStream contentStream = sysObject.getContent();
						File tempFile = File.createTempFile(sysObject.getObjectName() + ".", "." + sysObject.getFormat().getDOSExtension());
						tempFile.deleteOnExit();
						FileOutputStream output = new FileOutputStream(tempFile);
						IOUtils.copy(contentStream, output);
						IOUtils.closeQuietly(contentStream);
						IOUtils.closeQuietly(output);
						Program.launch(tempFile.getAbsolutePath());
					} else {
						MessageDialog.openInformation(HandlerUtil.getActiveShell(event), "No content", "No content available to open in editor.");
					}
				} catch (DfException e) {
					throw new LimeException(e);
				} catch (IOException e) {
					throw new LimeException(e);
				}
			}
		}
		return null;
	}

}
